<?php

namespace slinks\extensions\smarty;

use slinks\core\Templating\EngineInterface;
use slinks\core\Templating\TemplateNameParserInterface;
use slinks\core\DependencyInjection\ContainerInterface;

class SmartyEngine implements EngineInterface {

    private $smarty;
    private $parser;

    public function __construct($smartyLibDir, $templateDirs, $configDirs, $cacheDir, TemplateNameParserInterface $parser) {

        $this->parser = $parser;

        require_once($smartyLibDir . DIRECTORY_SEPARATOR . 'Smarty.class.php');

        $this->smarty = new \Smarty();
        $this->smarty->template_dir = $templateDirs;
        $this->smarty->compile_dir = $cacheDir . '/smarty/templates_c/';
        $this->smarty->cache_dir = $cacheDir . '/smarty/';
        $this->smarty->config_dir = $configDirs;
    }

    /**
     * Renders a template.
     *
     * @param mixed $name       A template name
     * @param array $parameters An array of parameters to pass to the template
     *
     * @return string The evaluated template as a string
     *
     * @throws \InvalidArgumentException if the template does not exist
     * @throws \RuntimeException         if the template cannot be rendered
     */
    public function render($name, array $parameters = array()) {
        $this->smarty->assign($parameters);
        return $this->smarty->fetch($name);
    }

    /**
     * Returns true if this class is able to render the given template.
     *
     * @param string $name A template name
     *
     * @return Boolean True if this class supports the given resource, false otherwise
     */
    public function supports($name) {
        $template = $this->parser->parse($name);

        return 'tpl' === $template['engine'];
    }

    public function addPluginDir($pluginDir) {
        $this->smarty->addPluginsDir($pluginDir);
    }

}
